package com.fingard.dsp.bank.directbank.abc02;

import com.fingard.dsp.bank.dbobj.receipt.ReceiptData;
import com.fingard.dsp.bank.dbobj.receipt.ReceiptDataHelper;
import com.fingard.dsp.bank.directConfig.ReceiptProConfig;
import com.fingard.dsp.bank.directbank.abc02.receiptpro.ABC02ReceiptProCMRA25;
import com.fingard.dsp.bank.directbank.abc02.receiptpro.ABC02ReceiptProFtp;
import com.fingard.dsp.bank.directbank.bankInterface.IReceiptPro;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.ReqQryReceipt;
import com.fingard.dsp.bank.reqrespobj.downloadreceipt.RetAtsReceipt;
import com.fingard.io.FileHelper;
import com.fingard.text.StringHelper;

import java.io.File;
import java.math.BigDecimal;
import java.util.Date;

/**
 * 农行电子回单
 */
public class ABC02ReceiptPro extends ABC02Base implements IReceiptPro {

    public RetAtsReceipt qryReceiptOneDay(ReceiptProConfig pConfig, ReqQryReceipt pReqReceipt, Date pOneDay) throws Exception {
    	String downType = getBankConfig().getValueAsString("receiptRequestType");
    	
    	String downType2 = bankFront.getStrValueByFor("receiptDownloadType", "");
    	if(StringHelper.hasAnyChar(downType2)){
    		downType = downType2;//前置机的配置覆盖config
    	}
    	
    	if("ftp".equalsIgnoreCase(downType) || "sftp".equalsIgnoreCase(downType) || "localhost".equalsIgnoreCase(downType)){
    		ABC02ReceiptProFtp receiptProFtp = new ABC02ReceiptProFtp();
    		receiptProFtp.reqHeader = this.reqHeader;
    		receiptProFtp.bankFront = this.bankFront;
    		receiptProFtp.setSbLog(this.sbLog);
    		receiptProFtp.setLogFlushTime(this.logFlushTime);
			return receiptProFtp.qryReceiptOneDay(pConfig, pReqReceipt, pOneDay);
    	}else{//CMRA25
    		WriteBankLogLn("downType:"+downType);
	    	ABC02ReceiptProCMRA25 receiptProCMRA25 = new ABC02ReceiptProCMRA25();
	    	receiptProCMRA25.reqHeader = this.reqHeader;
	    	receiptProCMRA25.bankFront = this.bankFront;
	    	receiptProCMRA25.setSbLog(this.sbLog);
	    	receiptProCMRA25.setLogFlushTime(this.logFlushTime);
			return receiptProCMRA25.qryReceiptOneDay(pConfig, pReqReceipt, pOneDay);
    	}
    }
    
	
	/**公共方法，下载的日期目录中提取pdf文件*/
	protected void getPdfFiles(ReceiptProConfig pConfig, ReqQryReceipt pReqReceipt, Date pOneDay, String pReceiptDir){
		ReceiptDataHelper receiptHelper = null;//回单数据保存类，分区分表
		try{
        	receiptHelper = new ReceiptDataHelper(pReqReceipt.reqHeader.tenant, pOneDay);
        	File receiptDir = new File(pReceiptDir);
        	
        	int[] retVals = getPdfLoop(pConfig, pReqReceipt, pOneDay, receiptHelper, receiptDir);
        	//[0]总数 [1]新增 [2]已存在
            WriteBankLogLn("目录"+pReceiptDir+"\r\n遍历总数"+retVals[0]+"，新增"+retVals[1]+"条，已存在"+retVals[2]+"条");
        	
		}catch(Exception ex){
        	this.WriteBankLogLn(ex);
        }finally{
        	if(receiptHelper != null){
        		receiptHelper.close();
        	}
        }
	}
    
    /**公共方法，提取pdf文件，农行是所有账号的回单一起提供，遍历所有pdf
     [0]总数 [1]新增 [2]已存在*/
    protected int[] getPdfLoop(ReceiptProConfig pConfig, ReqQryReceipt pReqReceipt, Date pOneDay, ReceiptDataHelper pReceiptHelper, File pDir){
		int[] retVals = new int[3];
		retVals[0] = 0;//总pdf个数
		retVals[1] = 0;//新增
		retVals[2] = 0;//已存在
    	File[] files = pDir.listFiles();
    	for (File eachFile : files) {
    		try{
    			if(eachFile.isDirectory()){
        			int[] subVals = getPdfLoop(pConfig, pReqReceipt, pOneDay, pReceiptHelper, eachFile);
        			retVals[0] = retVals[0] + subVals[0];
        			retVals[1] = retVals[1] + subVals[1];
        			retVals[2] = retVals[2] + subVals[2];
        		}
    			String[] nameAndExt = StringHelper.splitFileNameAndExt(eachFile.getName());
                if ("pdf".equalsIgnoreCase(nameAndExt[1])) {
                	retVals[0] = retVals[0] + 1;
                    //[0]银企通编号_[1]8位日期_[2]本方账号_[3]日志号_[4]对方账号_[5]交易金额（绝对值)_[6]电子回单编号_[7]借贷标志.pdf
                	//10999953500000027_20191106_10431201040003421_205219262_10431101046955980_3.84_39700205219262135758_D.pdf
                    String[] nameSp = nameAndExt[0].split("_");
                    if (nameSp.length != 8) {
                        WriteBankLogLn("回单文件:" + eachFile.getName() + "文件名格式不符合预期");
                        continue;
                    }
                    ReceiptData eachData = new ReceiptData();
                    eachData.istNbr = nameSp[6];
                    eachData.ownAct = nameSp[2];
                    eachData.setBusDate(pOneDay);
                    //重命名
                    String renameToPath = pConfig.getSaveSubDir(pReqReceipt.reqHeader, pOneDay) + File.separator + String.valueOf(eachData.busDate) + File.separator + eachData.ownAct;
                    FileHelper.mkdirsIfNotExists(renameToPath);
                    renameToPath += File.separator + nameSp[2] + "_" + nameSp[3] + "_" + nameSp[6] + "." + StringHelper.getFileExt(eachFile.getName());//eachFile.getName();
                    File destFile = new File(renameToPath);
                    boolean reResult;
                    if(destFile.exists()){
                    	reResult = true;
                    }else{
                    	reResult = eachFile.renameTo(destFile);
                    }
                    if(reResult){
                    	eachData.localFile = StringHelper.getRelativePath(destFile.getAbsolutePath(), pConfig.localSaveMainDir);
                        eachData.srcFile = eachFile.getName();
                        eachData.receiptNo = nameSp[3];
                        eachData.busRef = nameSp[3];
                        eachData.bank = "103";
                        eachData.srcSys = "ABC02";
                        
                        if(!String.valueOf(eachData.busDate).equals(nameSp[1])){
                        	WriteBankLogLn("提取的日期"+nameSp[1]+"不符合预期"+String.valueOf(eachData.busDate)+"，回单文件名:" + eachFile.getName());
                        	eachData.downInfo = nameSp[1]+"-文件中提取的日期";
                        }
                        
                        eachData.oppActNum = nameSp[4];
                        eachData.amount = new BigDecimal(nameSp[5]);
                        if("D".equalsIgnoreCase(nameSp[7])){
                        	eachData.moneyWay = "1";
                        }else if("C".equalsIgnoreCase(nameSp[7])){
                        	eachData.moneyWay = "2";
                        }
                        
                        eachData.downState = "2";
                        eachData.downTime = new Date();
                        
                        int inRe = pReceiptHelper.insertIfNotExist(eachData, true);
                        if(inRe>0){
                        	retVals[1] = retVals[1] + 1;
                        }else if(inRe == 0){
                        	retVals[2] = retVals[2] + 1;
                        }
                        WriteBankLogLn(eachData.receiptNo+"写入数据库，影响行数："+inRe);
                        if(eachData.ownAct.length()>15){
                        	int startIdx = eachData.ownAct.length()-15;
                        	eachData.ownAct = eachData.ownAct.substring(startIdx, eachData.ownAct.length());
                        	inRe = pReceiptHelper.insertIfNotExist(eachData, true);
                        	WriteBankLogLn(eachData.receiptNo+"同时保存到15位本方账号"+eachData.ownAct+"，写入数据库影响行数："+inRe);
                        }
                    }else{
                    	WriteBankLogLn(eachData.receiptNo+"重命名失败：\r\n"+eachFile.getAbsolutePath()+"\r\n重命名为：\r\n"+renameToPath);
                    }
                }
    		}catch(Exception ex){
    			WriteBankLogLn(ex, eachFile.getAbsolutePath());
    		}
        }
    	return retVals;
	}
}
